package com.gl.mobile.activities;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;

import com.gl.mobile.R.string;
import com.gl.mobile.constants.Constants;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;

public class FiltrarLibrosActivity extends Activity {
	
	private ScrollView layout;
	
	private TableLayout tableLayout;
	
	private Button applyFilter;
	
	private List<CheckBox> checksArray;
	
	private ArrayList<Integer> selectedCategories;
	
	@Override
    public void onCreate(Bundle savedInstanceState) 
	{
        super.onCreate(savedInstanceState);
        
        Bundle bundle = getIntent().getExtras();
        if(bundle!=null)
        {
	        if( bundle.containsKey("selectedCategories") )
	        	selectedCategories = bundle.getIntegerArrayList("selectedCategories");
        }
        
        tableLayout = new TableLayout(this);
        layout = new ScrollView(this);
        layout.setVerticalScrollBarEnabled(true);
        
        TableRow buttonRow = new TableRow(this);
        applyFilter = new Button(this);
        applyFilter.setText(string.aplicar_filtro);
        applyFilter.setOnClickListener( new View.OnClickListener() 
        {
        	public void onClick(View v) 
        	{
        		Intent intent = new Intent( getApplicationContext(), CustomListViewActivity.class );
        		Bundle bundle = new Bundle();
        		bundle.putIntegerArrayList("categories", getSelectedCategories());
        		intent.putExtras(bundle);
        		startActivity(intent);
            }
        	
        });

        buttonRow.addView(applyFilter);
        tableLayout.addView(buttonRow);
        
        pedirCategorias();
        
        
    }
	
	private void pedirCategorias()
	{
		
		new Thread(new Runnable()
        {
	        @Override
	        public void run() 
	        {
	        	String URL = Constants.BASE_PATH + "/rest/listarCategorias/";
	            String result = new String();
	            
	        	HttpClient httpclient = new DefaultHttpClient();  
	            HttpGet request = new HttpGet(URL);  
	            ResponseHandler<String> handler = new BasicResponseHandler();
	            	            
	            try {  
	                result = httpclient.execute(request, handler);  
	            } catch (ClientProtocolException e) {  
	                e.printStackTrace();  
	            } catch (IOException e) {  
	                e.printStackTrace();  
	            }  
	            httpclient.getConnectionManager().shutdown();
	            
    			mostrarCategorias( result );
    			
	        }
        }).run();
		
		setContentView( layout );
	}
	
	private void mostrarCategorias( String result )
	{
		JSONArray categorias;
		try 
		{
			categorias = new JSONArray(result);
			checksArray = new ArrayList<CheckBox>();
			for (int i = 0; i < categorias.length(); i++) 
			{
				Boolean categorySelected = false;
				if( selectedCategories != null )
				{
					for( int j=0; j<selectedCategories.size(); j++ )
					{
						if( selectedCategories.get(j) == Integer.valueOf(categorias.getJSONObject(i).getInt("id")) )
							categorySelected = true;
					}
				}
				else
					categorySelected = true;
				
				TableRow row = new TableRow(this);
				
				CheckBox checkBox = new CheckBox(this);
				checkBox.setText( categorias.getJSONObject(i).getString("nombre") );
				checkBox.setId( categorias.getJSONObject(i).getInt("id") );
				
				if( categorySelected )
					checkBox.setChecked(true);
				else
					checkBox.setChecked(false);
				
				row.addView(checkBox);
				checksArray.add(checkBox);
				tableLayout.addView(row);
			}
			layout.addView(tableLayout);
			
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
	}
	
	private ArrayList<Integer> getSelectedCategories()
	{
		ArrayList<Integer> selectedItems = new ArrayList<Integer>();
		for ( int i = 0;i<checksArray.size(); i++ )
		{
			if( ((CheckBox)checksArray.get(i)).isChecked() )
				selectedItems.add( Integer.valueOf(checksArray.get(i).getId()) );
				
		}
		return selectedItems;
	}
    
}